package service;

import dao.CategoryDAO;
import dao.RecordDAO;
import entity.Category;
import entity.Record;
import util.DBUtil;

import java.util.Collections;
import java.util.List;

public class CategoryService {
    CategoryDAO categoryDAO = new CategoryDAO();
    RecordDAO recordDAO = new RecordDAO();

    public List<Category> list() {
        List<Category> categoryList = categoryDAO.list();
        for(Category c:categoryList) {
            List<Record> rs = recordDAO.list(c.id);//获取该分类下的所有Record记录
            c.setRecordNumber(rs.size());
        }
        Collections.sort(categoryList,(c1,c2)->c2.RecordNumber-c1.RecordNumber);

        return categoryList;
    }

    public void add(String name) {
        Category c = new Category();
        c.setName(name);
        categoryDAO.add(c);
    }

    public void update(int id, String name) {
        Category c = new Category();
        c.setName(name);
        c.setId(id);
        categoryDAO.update(c);
    }

    public void delete(int id) {
        categoryDAO.delete(id);

//        if(categoryDAO.list().isEmpty())
//            DBUtil.truncate("category");

    }
}
